/**
* MyFileUpload01
* @Author:  Jian Junbo
* @Email:   junbojian@qq.com
* @Create:  2017/9/17 15:14
* Copyright (c) 2017 Jian Junbo All rights reserved.
*
* Description:  简单的上传文件
 */
package main

import (
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

var hostURL string
var filePath string

func main() {
	flag.StringVar(&hostURL, "h", "http://192.168.42.33/file/Download", "host url")
	flag.StringVar(&filePath, "f", "/root/Downloads", "img file path")
	flag.Parse()
	http.HandleFunc("/upimg/", index)
	http.HandleFunc("/upimg/upload2", upload)
	http.HandleFunc("/getimg/", getImg)
	err := http.ListenAndServe(":81", nil)
	if err != nil {
		fmt.Println("服务器启动失败", err.Error())
		return
	}

}
func upload(writer http.ResponseWriter, request *http.Request) {
	request.ParseMultipartForm(32 << 20)
	//接收客户端传来的文件 uploadfile 与客户端保持一致
	file, handler, err := request.FormFile("uploadfile")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	//上传的文件保存在ppp路径下
	// ext := handler.Filename //获取文件后缀
	fileNewName := handler.Filename

	f, err := os.OpenFile(filePath+"/"+fileNewName, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	io.Copy(f, file)
	os.Chown(filePath+"/"+fileNewName, 1000, 1000)
	fmt.Fprintln(writer, `
	<!DOCTYPE html>
	<html>
	<head>
	<meta charset="utf-8">
	<title>上传文件</title>
	<style>
	button {    
		background-color: #4CAF50; /* Green */    
		border: none;    color: white;    padding: 16px 32px;    
		text-align: center;    
		text-decoration: none;    
		display: inline-block;    
		font-size: 16px;    
		margin: 4px 2px;    
		-webkit-transition-duration: 0.4s; /* Safari */    
		transition-duration: 0.4s;    
		cursor: pointer;
		} 
	button:hover {    
		background-color: #008CBA;    
		color: white;
	}
	</style>
	<script>
	function copyTXT(){
		var copyDOM = document.querySelector('#copy-txt'); //指定的DOM元素
		var range = document.createRange(); // 创建容器
		range.selectNode(copyDOM); // 选中需要复制的节点
		window.getSelection().addRange(range); // 执行选中元素
		var successful = document.execCommand('copy');// 执行 copy 操作
		var btnVal=document.getElementById("copy");
		try {
			
			var msg = successful ? 'successful' : 'unsuccessful';
			btnVal.innerHTML="已复制"
		} catch(err) {
			btnVal.innerHTML="失败"

		}
		window.getSelection().removeAllRanges(); // 移除选中的元素
		sleep(1000).then(() => {
			// 这里写sleep之后需要去做的事情
			btnVal.innerHTML="复制"
		})
		
	}
	function sleep (time) {
		return new Promise((resolve) => setTimeout(resolve, time));
	}
	</script>
	</head>
	<body>
	<div id="copy-txt">`+hostURL+"/"+fileNewName+`</div>
	<button id="copy" onclick="copyTXT()">复制</button>
	</body>
	</html>
	`)
}

func index(writer http.ResponseWriter, request *http.Request) {

	writer.Write([]byte(tpl))
}

func getImg(writer http.ResponseWriter, request *http.Request) {
	words := strings.Split(request.URL.Path, "/")
	if len(words) != 3 {
		fmt.Fprintln(writer, `<!DOCTYPE html>
		<html>
		<head>
		<meta charset="utf-8">
		<title>上传文件</title>
		</head>
		<body>
		<div>Resource Not Found!</div>
		</body>
		</html>
		`)
		return
	}
	fp := filePath + "/" + words[2]
	item, err := ioutil.ReadFile(fp)
	if err != nil {
		fmt.Fprintln(writer, `<!DOCTYPE html>
		<html>
		<head>
		<meta charset="utf-8">
		<title>上传文件</title>
		</head>
		<body>
		<div>Resource Not Found!</div>
		</body>
		</html>
		`)
		return
	}

	writer.Write(item)

}

const tpl = `<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>上传文件</title>				
	<style>
	
	body
	{
		background-color:#b0e0e6;
	}
	div
	{
		margin:auto;
		text-align:center;
	}

	</style>
</head>
<body>
<div>
<form enctype="multipart/form-data" class="center" action="/upimg/upload2" method="post"  target="iframe_a">
<input type="file" style="width:600px;"  name="uploadfile">
<input type="hidden"   name="token" value="{...{.}...}">
<input type="submit" style="width:200px;" value="upload">
</form>
<iframe src="/upimg/upload2" name="iframe_a" class="center" frameborder="0" width="800" height="100"></iframe>
</div>
</body>
</html>
`
